package br.skytef.stmanager.beans;

import java.io.IOException;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.skytef.stmanager.entities.ClienteEntity;
import br.skytef.stmanager.entities.UsuarioEntity;
import br.skytef.stmanager.utils.Consulta;
import br.skytef.stmanager.utils.Data;

@ManagedBean(name="CadastroClienteBean")
@SessionScoped
public class CadastroClienteBean {

	private ClienteEntity cliente;
	public ClienteEntity getCliente() {return cliente;}
	public void setCliente(ClienteEntity cliente) {	this.cliente = cliente;}

	private List<ClienteEntity> clientes;
	public List<ClienteEntity> getClientes() {return clientes;}
	public void setClientes(List<ClienteEntity> clientes) {this.clientes = clientes;}

	private String formulario = "none";
	public String getFormulario() {return formulario;}
	public void setFormulario(String formulario) {this.formulario = formulario;}


	private String consulta;
	public String getConsulta() {return consulta;}
	public void setConsulta(String consulta) {this.consulta = consulta;}

	private String listaView = "none";
	public String getListaView() {return listaView;}
	public void setListaView(String listaView) {this.listaView = listaView;}
	
	private HttpSession session;
	private UsuarioEntity usuario;

	public CadastroClienteBean() {
		super();
		formulario = "none";
		listaView = "none";
		cliente = clienteBranco();
		FacesContext ctx = FacesContext.getCurrentInstance();
		session = (HttpSession) ctx.getExternalContext().getSession(false);
		usuario = (UsuarioEntity)session.getAttribute("usuario");
		if(usuario == null)
			new LoginBean().encerraSessao();
	}

	public void SalvarCliente() throws IOException{
		cliente = clienteBranco();
		consulta = null;
		DashboardBean.pageCadastrarCliente();
	}

	public void pesquisar(){
		cliente = clienteBranco();
		if(!consulta.equals("")&&consulta != null){
			cliente = new Consulta().cliente(consulta);
			if(cliente != null){
				formulario = "";
			}else{
				clientes = new Consulta().clientes(consulta);
				if(!clientes.isEmpty()){
					if(clientes.size() == 1){
						cliente = clientes.get(0);
						formulario = "";
					}else{
						cliente = clientes.get(0);
						listaView = "";
					}
				}
			}
		}
	}
	public void clienteSelecionado(){
		listaView = "none";
		formulario = "";
	}

	public String novo(){
		cliente = clienteBranco();
		formulario = "";
		return null;
	}

	private ClienteEntity clienteBranco(){
		formulario = "none";
		return new ClienteEntity(" ", " ", 0, 0, " ", " ", " ", " ", " ", " ", " ", " ", " ", 0, " ", " ", " ", " ", new Data().DtTime(), null, usuario.getId(), 0, 0, " ", 0, 0,0);
	}
}
